import { defineStore } from 'pinia'
import { ref } from 'vue'
import { localStorage } from '../utils/storage'

export const useProductStore = defineStore('product', () => {
  // 从本地存储初始化
  const preloadedProducts = ref(localStorage.get('preloaded_products'))
  const recentViews = ref(localStorage.get('recent_views') || [])

  const setPreloadedProducts = (products) => {
    preloadedProducts.value = products
    localStorage.set('preloaded_products', products, 5 * 60 * 1000) // 5分钟缓存
  }

  const addRecentView = (product) => {
    const exists = recentViews.value.find(p => p.id === product.id)
    if (!exists) {
      recentViews.value.unshift(product)
      if (recentViews.value.length > 20) {
        recentViews.value.pop()
      }
      localStorage.set('recent_views', recentViews.value)
    }
  }

  return {
    preloadedProducts,
    recentViews,
    setPreloadedProducts,
    addRecentView
  }
}) 